package com.opdar.platform.core.base;

import org.springframework.util.StreamUtils;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by shiju on 2017/1/23.
 */
public class Context {
    static ThreadLocal<ServletRequest> REQUEST = new ThreadLocal<ServletRequest>();
    static ThreadLocal<ServletResponse> RESPONSE = new ThreadLocal<ServletResponse>();
    static final String APPLICATION_CONTEXT = "applicationContext";
    static Map<String, String> RESOURCE_MAPPING = new HashMap<String, String>();
    static byte[] getBody(String contentType){
        try {
            if(REQUEST.get().getContentType().contains(contentType)){
                return StreamUtils.copyToByteArray(REQUEST.get().getInputStream());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static HttpServletRequest getRequest() {
        return (HttpServletRequest) REQUEST.get();
    }

    public static HttpServletResponse getResponse() {
        return (HttpServletResponse) RESPONSE.get();
    }

    public static void putAttribute(String key, Object value) {
        REQUEST.get().setAttribute(key,value);
    }

    public static void putResourceMapping(String key, String value) {
        RESOURCE_MAPPING.put(key,value);
    }
}
